<!DOCTYPE HTML>
<html>

<head>
  <meta charset="utf-8">
  <style>
    #field {
      position: relative;
      width: 200px;
      height: 150px;
      border: 10px solid black;
      background-color: #00FF00;
      cursor: pointer;
      overflow: hidden;
    }
    #ball {
      position: absolute;
      left: 0;
      top: 0;
      width: 40px;
      height: 40px;
      transition: all 1s;
    }
  </style>
</head>

<body style="height:2000px">

  Click on a field to move the ball there.
  <br> The ball should never leave the field.


  <div id="field">
    <img src="https://en.js.cx/clipart/ball.svg" id="ball"> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
    . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
  </div>

  <script>
    const fieldEl = document.querySelector('#field')
    const ballEl = ball

    const fieldElCwidth = fieldEl.clientWidth
    const fieldElCheight = fieldEl.clientHeight

    const ballWidth = 40
    const ballHeight = 40
    
    fieldEl.addEventListener('click', (e) => {
      let fieldCoords = fieldEl.getBoundingClientRect();
      const { x, y } = fieldCoords
      const { clientX, clientY } = e
      const { clientTop, clientLeft } = fieldEl
      let offsetX = clientX - clientLeft - x
      let offsetY = clientY - clientTop - y

      console.log(fieldCoords, e, offsetX, offsetY)

      const ballWidthHalf = ballWidth / 2
      const ballHeightHalf = ballHeight / 2

      let ballLeft = offsetX - ballWidthHalf
      let ballTop = offsetY - ballWidthHalf

      // 如果球超出了边界的话
      if (offsetX + ballWidthHalf >= fieldElCwidth) {
        ballLeft = fieldElCwidth - ballWidth
      } else if (offsetX - ballWidthHalf <= 0) {
        ballLeft = 0
      }

      if (offsetY + ballHeightHalf >= fieldElCheight) {
        ballTop = fieldElCheight - ballHeight
      } else if (offsetY - ballHeightHalf <= 0) {
        ballTop = 0
      }


      ballEl.style.top = ballTop + 'px'
      ballEl.style.left = ballLeft + 'px'
    })

  </script>

</body>
</html>